package com.richapp.launcher.service;

import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.jack.netty.log.LoggerManager;
import com.jack.netty.tcp.server.ServerSessionManager;
import com.jack.util.date.DateUtil;
import com.richapp.launcher.R;
import com.richapp.launcher.busevent.EventTimeTick;
import com.richapp.launcher.busevent.EventUnbindBox;
import com.richapp.launcher.control.MoveControl;
import com.richapp.launcher.control.PageControl;
import com.richapp.launcher.control.PhoneControl;
import com.richapp.launcher.control.VolumeControl;
import com.richapp.launcher.database.infrared.dao.BrandDao;
import com.richapp.launcher.database.infrared.dao.BrandModelDao;
import com.richapp.launcher.database.system.dao.ActionInfraredModelDao;
import com.richapp.launcher.database.system.dao.ActionModelDao;
import com.richapp.launcher.database.system.dao.BoxLoginDao;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.dao.BoxPhoneDao;
import com.richapp.launcher.database.system.dao.ConditionSensorModelDao;
import com.richapp.launcher.database.system.dao.ConditionStatusModelDao;
import com.richapp.launcher.database.system.dao.ConditionTimeModelDao;
import com.richapp.launcher.database.system.dao.DeviceDayPowerConsumptionDao;
import com.richapp.launcher.database.system.dao.DeviceModelDao;
import com.richapp.launcher.database.system.dao.DeviceModelHistoryDao;
import com.richapp.launcher.database.system.dao.DeviceMonthPowerConsumptionDao;
import com.richapp.launcher.database.system.dao.RoomModelDao;
import com.richapp.launcher.database.system.dao.SceneModelDao;
import com.richapp.launcher.database.system.dao.SystemValueModelDao;
import com.richapp.launcher.database.system.dao.UserLoginDao;
import com.richapp.launcher.database.system.dao.UserMachineButtonDao;
import com.richapp.launcher.database.system.dao.UserMachineDao;
import com.richapp.launcher.database.system.dao.UserModelDao;
import com.richapp.launcher.database.system.mode.BoxLogin;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.database.system.mode.UserLogin;
import com.richapp.launcher.gpio.GPIOServer;
import com.richapp.launcher.net.box.tcp.server.BoxServer;
import com.richapp.launcher.net.mobile.server.UserServer;

import com.richapp.launcher.receiver.NetWorkChangeReceiver;
import com.richapp.launcher.serialport.gateway.command.AddCmd;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;

import java.io.File;
import java.util.List;

import de.greenrobot.event.EventBus;
import hdp.http.HdpKit;
import io.netty.channel.ChannelHandlerContext;


/**
 * Created by jack on 2015/4/8 0008.
 */
public class BackService extends Service{
    private String clientName = "客户端";
    private static final String TAG = BackService.class.getName();
    private NetWorkChangeReceiver netWorkChangeReceiver = null;
    private BoxModelDao boxModelDao = null;
    private UserLoginDao userLoginDao = null;
    private BoxLoginDao boxLoginDao = null;




    private static final String ZIVEN_BUTTON_WPS_SHORT_PRESS="com.ufo.wps.short.press";
    private static final String ZIVEN_BUTTON_WPS_LONG_PRESS="com.ufo.wps.long.press";
    private static final String ZIVEN_BUTTON_WPS_LONGL_PRESS="com.ufo.wps.longl.press";


    private BroadcastReceiver wpsReceiver;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //return super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        EventBus.getDefault().register(this);

        boxModelDao = new BoxModelDao(this);

        netWorkChangeReceiver = new NetWorkChangeReceiver();
        registerReceiver(netWorkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

        wpsReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if(ZIVEN_BUTTON_WPS_LONG_PRESS.equals(intent.getAction())){
                    String msg = "长按|WPS键!";
                    LoggerManager.getInstance().getiLogger().info(getClass(),msg);
                    Toast toast = Toast.makeText(BackService.this, msg, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();

                }else if(ZIVEN_BUTTON_WPS_SHORT_PRESS.equals(intent.getAction())){
                    String msg = "短按|WPS键!";
                    LoggerManager.getInstance().getiLogger().info(getClass(),msg);
                    Toast toast = Toast.makeText(BackService.this, msg, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();

//                    AddCmd.getInstance().blindAdd();
                }else if (ZIVEN_BUTTON_WPS_LONGL_PRESS.equals(intent.getAction())){
                    String msg = "长按5秒|WPS键!";
                    LoggerManager.getInstance().getiLogger().info(getClass(),msg);
                    Toast toast = Toast.makeText(BackService.this, msg, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    wpsUnbinBox();
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(ZIVEN_BUTTON_WPS_LONG_PRESS);
        filter.addAction(ZIVEN_BUTTON_WPS_SHORT_PRESS);
        filter.addAction(ZIVEN_BUTTON_WPS_LONGL_PRESS);
        registerReceiver(wpsReceiver,filter);

        //加载蜂鸣器参数
        initGPIO();

        //设置当前主机信息
        setSystemInfo();

        //获取当前设备信息
        getDeviceInfo(this);

        //初始化UI信息
        initUIInfo();

        //启动信鸽
        //startXinge();

        //实例化用户控制
        initUserControl();

        //deng
        showNetInfoLight();

        //bind hdpi
        HdpKit.getinstance().bindHdpService(this);

        //保持服务
        Notification notification = new Notification();
        startForeground(1, notification);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkChangeReceiver);
        unregisterReceiver(wpsReceiver);
        HdpKit.getinstance().unbindHdpService();
    }


    private void initGPIO(){
        GPIOServer.getInstance().setBase(getResources().getInteger(R.integer.gpio_base_time));

        GPIOServer.getInstance().setVALUE_OPEN(getResources().getInteger(R.integer.gpio_value_open));
        GPIOServer.getInstance().setVALUE_CLOSE(getResources().getInteger(R.integer.gpio_value_close));

        GPIOServer.getInstance().setGROUP_FENG_MING_QI(getResources().getString(R.string.gpio_group_feng_ming_qi).charAt(0));
        GPIOServer.getInstance().setID_FENG_MING_QI(getResources().getInteger(R.integer.gpio_id_feng_ming_qi));

        GPIOServer.getInstance().setGROUP_WIFI(getResources().getString(R.string.gpio_group_wifi).charAt(0));
        GPIOServer.getInstance().setID_WIFI(getResources().getInteger(R.integer.gpio_id_wifi));

        GPIOServer.getInstance().setGROUP_LAN(getResources().getString(R.string.gpio_group_lan).charAt(0));
        GPIOServer.getInstance().setID_LAN(getResources().getInteger(R.integer.gpio_id_lan));

        GPIOServer.getInstance().setGROUP_YELLOW_LED(getResources().getString(R.string.gpio_group_yellow_led).charAt(0));
        GPIOServer.getInstance().setID_YELLOW_LED(getResources().getInteger(R.integer.gpio_id_yellow_led));
    }

    /**
     * 初始化用户控制
     */
    private void initUserControl(){
        //audio
        VolumeControl.getInstance().setContext(this);
        //page
        PageControl.getInstance().setContext(this);
        //move
        MoveControl.getInstance().setContext(this);
        //phone
        PhoneControl.getInstance().setContext(this);
    }

    /**
     * 启动信鸽线程
     */
//    private void startXinge(){
//        XGPushConfig.enableDebug(this, false);
//        XGPushConfig.setInstallChannel(this, "RICHAPP");
//        XGPushConfig.setGameServer(this, "上海一区");
//        XGPushManager.setTag(this, "BOX");
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                boolean runFlag = true;
//                try{
//                    while(runFlag){
//                        BoxModel currentBox = boxModelDao.getCurrentBox();
//                        if(currentBox.getUserName() == null || "".equals(currentBox.getUserName())){
//
//                        }else{
//                            XGPushManager.registerPush(BackService.this, currentBox.getUserName());
//                            runFlag = false;
//                        }
//                        Thread.sleep(1000);
//                    }
//                }catch (Exception e){
//                    Log.e(TAG,"启动信鸽线程错误:"+e.getMessage());
//                }
//            }
//        }).start();
//    }

    /**
     * 配置当前主机信息
     */
    private void setSystemInfo(){
        BoxModel bm = boxModelDao.getCurrentBox();
        Log.v(TAG, "主机地址:" + bm.getBoxInsideIp());
        Log.v(TAG, "主机ID:" + bm.getBoxCpuId());
    }

    private void initUIInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Thread.sleep(3000);
                    UserServer.getInstance().userInfoUpdate();
                }catch (Exception e){
                    Log.e(TAG,"更新用户UI信息错误:"+e.getMessage());
                }
            }
        }).start();
    }

    private void showNetInfoLight(){
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        NetworkInfo lanNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);


        if(wifiNetInfo != null){
            if(wifiNetInfo.isConnected()){
                GPIOServer.getInstance().openWifiLight();
            }else{
                GPIOServer.getInstance().closeWifiLight();
            }
        }

        if(lanNetInfo != null){
            if(lanNetInfo.isConnected()){
                GPIOServer.getInstance().openLanLight();
            }else{
                GPIOServer.getInstance().closeLanLight();
            }
        }

        if(mobNetInfo != null){
            if(mobNetInfo.isConnected()){

            }else{

            }
        }
    }

    private String getDeviceInfo(Context context) {
        String result = null;
        try{
            org.json.JSONObject json = new org.json.JSONObject();
            android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                    .getSystemService(Context.TELEPHONY_SERVICE);

            String device_id = tm.getDeviceId();

            android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);

            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);

            if( TextUtils.isEmpty(device_id) ){
                device_id = mac;
            }

            if( TextUtils.isEmpty(device_id) ){
                device_id = android.provider.Settings.Secure.getString(context.getContentResolver(),android.provider.Settings.Secure.ANDROID_ID);
            }

            json.put("device_id", device_id);
            result = json.toString();

            Log.d(TAG,"deviceInfo:"+result);
        }catch(Exception e){
            Log.e(TAG,e.getMessage());
        }
        return result;
    }

    public void onEventMainThread(EventTimeTick eventTimeTick){
        LoggerManager.getInstance().getiLogger().info(getClass(),"backService 收到 timeTicker 事件");
    }

    public void wpsUnbinBox(){
        BoxModel bm = boxModelDao.getCurrentBox();
        JSONObject jsonObject=new JSONObject();
        String clientid ="";
        jsonObject.put("type",66);
        jsonObject.put("userName",bm.getUserName());
        jsonObject.put("boxCpuId",bm.getBoxCpuId());
        jsonObject.put("currentBoxCpuId",bm.getBoxCpuId());
        jsonObject.put("HEAD_IS_REPLY",false);
        jsonObject.put("lastHandelTime", DateUtil.getDateLong());

        UserServer userServer= UserServer.getInstance();

        GPIOServer.getInstance().alarmBeep();
        GPIOServer.getInstance().lightFlash();

        userServer.doUnbindBox(clientid,jsonObject);

    }


}
